﻿using System;
using System.Linq;
using ForumsBrowser.BusinessObjects;
using ForumsBrowser.ServiceContracts;
using ForumsBrowser.SiteAccess;

namespace ForumsBrowser.ObjectGateway
{
    internal static class ThreadGetAction
    {
        internal static Thread Execute(string url)
        {
            Thread result = null;

            var data = ServiceFactory.Service.GetThread(url);

            if (data != null)
            {
                
                var users = data.Users.Select(user => TranslateUserAction.Execute(user)).ToList().ToLookup(u => u.Id);
                var messages = TranslateMessagesAction.Execute(data.Messages);

                result = new Thread()
                {
                    Id = data.Threads.Id,
                    Title = data.Threads.Topic,
                    Url = data.Threads.Url,
                    Author = users[data.Threads.AuthorId].First(),
                    CreatedOn = data.Threads.CreatedOn.FromXmlToDateTime().Value,
                    Replies = data.Threads.Replies,
                    Type = data.Threads.Type,
                    Views = data.Threads.Views,
                    
                };

                foreach (var message in data.Messages)
                    messages.First(m => m.Id == message.Id).Author = users[message.AuthorId].First();

                result.Messages.AddRange(messages.Where(m => !m.Deleted));

                var reply = data.Threads.LastReply;
                if (reply != null)
                {
                    result.LastReplier = users[data.Messages[data.Threads.LastReply.Id].AuthorId].First();
                    result.LastRepliedOn = data.Threads.LastReply.Date.FromXmlToDateTime();
                }
            }

            return result;
        }
    }
}
